package com.aizuda.boot.modules.business.contract.service.impl;

import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.business.contract.entity.*;
import com.aizuda.boot.modules.business.contract.entity.vo.FieldTreeDTO;
import com.aizuda.boot.modules.common.constant.enums.ResponseCodeEnum;
import com.aizuda.boot.modules.business.contract.mapper.*;
import com.aizuda.boot.modules.business.contract.service.ContractWorkflowFormFieldService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 合同流程与表单字段关联Service实现类
 *
 * @Author sangyirong
 * @Version 1.0
 * @Date 2025/5/20 13:36
 */
@Service
public class ContractWorkflowFormFieldServiceImpl extends ServiceImpl<ContractWorkflowFormFieldMapper, ContractWorkflowFormFieldEntity> implements ContractWorkflowFormFieldService {

    @Resource
    private ContractWorkflowModuleMapper contractWorkflowModuleMapper;

    @Resource
    private ContractFieldMapper contractFieldMapper;

    @Resource
    private ContractModuleMapper contractModuleMapper;

    @Resource
    private ContractModuleFieldMapper contractModuleFieldMapper;

    @Override
    public SingleResponse<List<FieldTreeDTO>> getFieldTree(Long workflowId) {
        // 校验数据
        if (null == workflowId) {
            return SingleResponse.failure(ResponseCodeEnum.PARAM_BINDING_EXCEPTION.getCode(), ResponseCodeEnum.PARAM_BINDING_EXCEPTION.getMsg());
        }
        // 获取所有启用模块
        List<Integer> moduleIds = contractWorkflowModuleMapper.selectList(new LambdaQueryWrapper<ContractWorkflowModuleEntity>()
                        .eq(ContractWorkflowModuleEntity::getWorkflowId, workflowId)
                        .select(ContractWorkflowModuleEntity::getModuleId))
                .stream().map(ContractWorkflowModuleEntity::getModuleId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(moduleIds)) {
            return SingleResponse.failure(ResponseCodeEnum.PARAM_BINDING_EXCEPTION.getCode(), "无启用字段");
        }

        // 获取所有启用的字段
        List<Long> fields = this.list(new LambdaQueryWrapper<ContractWorkflowFormFieldEntity>()
                        .in(ContractWorkflowFormFieldEntity::getModuleId, moduleIds)
                        .eq(ContractWorkflowFormFieldEntity::getIsEnabled, true)
                        .select(ContractWorkflowFormFieldEntity::getFieldId))
                .stream().map(ContractWorkflowFormFieldEntity::getFieldId).collect(Collectors.toList());

        // 根据字段ID构建字段树
        return SingleResponse.of(this.buildFieldTree(moduleIds, fields));
    }

    public List<FieldTreeDTO> buildFieldTree(List<Integer> moduleIds, List<Long> fields) {
        // 获取所有模块
        List<ContractModuleEntity> moduleEntities = contractModuleMapper.selectByIds(moduleIds);

        // 获取所有字段
        List<ContractFieldEntity> fieldEntities = contractFieldMapper.selectByIds(fields);

        // 获取字段id映射
        Map<Long, ContractFieldEntity> fieldEntityMap = fieldEntities.stream().collect(Collectors.toMap(ContractFieldEntity::getId, item -> item));

        // 构建结果
        ArrayList<FieldTreeDTO> result = new ArrayList<>();
        // 获取模块字段关联
        Map<Integer, List<ContractModuleFieldEntity>> moduleFieldMap = contractModuleFieldMapper.selectList(new LambdaQueryWrapper<ContractModuleFieldEntity>()
                        .in(ContractModuleFieldEntity::getModuleId, moduleIds)
                        .in(ContractModuleFieldEntity::getFieldId, fields))
                .stream().collect(Collectors.groupingBy(ContractModuleFieldEntity::getModuleId));

        for (ContractModuleEntity moduleEntity : moduleEntities) {
            Integer moduleId = moduleEntity.getId();
            List<ContractModuleFieldEntity> contractModuleFieldEntities = moduleFieldMap.get(moduleId);
            if (CollectionUtils.isEmpty(contractModuleFieldEntities)){
                continue;
            }
            // 获取当前模块下包含的字段
            List<ContractFieldEntity> collect = contractModuleFieldEntities.stream().map(item -> {
                Long fieldId = item.getFieldId();
                ContractFieldEntity fieldEntity = fieldEntityMap.get(fieldId);
                return fieldEntity;
            }).collect(Collectors.toList());
            FieldTreeDTO fieldTreeDTO = new FieldTreeDTO();
            fieldTreeDTO.setModuleId(moduleId);
            fieldTreeDTO.setModuleName(moduleEntity.getModuleName());
            // 构建字段树
            fieldTreeDTO.setFieldTreeNode(this.buildFieldTreeNode(null, collect));
            result.add(fieldTreeDTO);
        }
        return result;
    }

    public List<FieldTreeDTO.FieldTreeNode> buildFieldTreeNode(Long parentFieldId, List<ContractFieldEntity> fieldEntities){
        List<FieldTreeDTO.FieldTreeNode> fieldTreeNodes = fieldEntities.stream().filter(item -> item.getParentFieldId() == parentFieldId)
                .map(item -> {
                    FieldTreeDTO.FieldTreeNode fieldTreeNode = new FieldTreeDTO.FieldTreeNode();
                    fieldTreeNode.setFieldId(item.getId());
                    fieldTreeNode.setFieldName(item.getFieldName());
                    return fieldTreeNode;
                }).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(fieldTreeNodes)){
            return null;
        }else {
            return fieldTreeNodes.stream().map(item -> {
                item.setChildren(buildFieldTreeNode(item.getFieldId(), fieldEntities));
                return item;
            }).collect(Collectors.toList());
        }
    }
}